//
//  APIBaseNetManager.m
//  InsuranceMarketing
//
//  Created by initial on 2018/1/25.
//  Copyright © 2018年 initial. All rights reserved.
//

#import "TooleClass.h"
#import "APIBase.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"
#import <CommonCrypto/CommonCrypto.h>
#import <Bugly/Bugly.h>
@interface APIBase ()

@property(nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation APIBase

+ (instancetype)sharedNetManager
{
    static id sharedNetManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedNetManager = [[super allocWithZone:NULL] init];
    });
    return sharedNetManager;
}

- (AFHTTPSessionManager *)sessionManager{
    if (!_sessionManager) {
        _sessionManager =[AFHTTPSessionManager manager];
    }
    return _sessionManager;
}

- (NSURLSessionDataTask * )requestWithMethod:(HttpRequestType)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters done:(void (^)(NSURLSessionDataTask * , id ))done fail:(void (^)(NSURLSessionDataTask * , NSError * ))fail{
    
    
    
    //用于对成功后的处理
    void (^responseSuccessBlock)(NSURLSessionDataTask *task, id responseObject) = ^(NSURLSessionDataTask *task, id responseObject) {
 
        NSInteger statusCode = [self showResponseCode:task];
        if (statusCode==294) {

        }
        if (statusCode==295) {
            
        }
        if (statusCode != 200 && statusCode !=429 &&statusCode != 0) {
//            [Bugly reportException:[NSException exceptionWithName:@"成功异常日志" reason:[NSString stringWithFormat:@"%@\n返回结果：%@",[task.currentRequest URL].absoluteString,responseObject] userInfo:nil]];
        }
        
        done(task, responseObject);
        
    };
    
    //对失败后结果处理
    void (^responseFailBlock)(NSURLSessionDataTask *task, NSError *error)=^(NSURLSessionDataTask *task, NSError *error){
        fail(task,error);

      //  NSInteger code = [self showResponseCode:task];
//        NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
//
//        VMLog(@"")
//        switch (code) {
//            case 401:
//
//               // [task.currentRequest URL].absoluteString = @"请求校验不通过";
//                break;
//
//            default:
//                break;
//        }
//        ;
        
        [Bugly reportException:[NSException exceptionWithName:@"失败异常日志" reason:[NSString stringWithFormat:@"%@\n错误日志：%@",[task.currentRequest URL].absoluteString, [error userInfo] ] userInfo:nil]];
    };
    
    
    //    NetManagerShare.sessionManager = [AFHTTPSessionManager manager]; //TODO: 董森森修改manager为每次请求产生一个产生内存泄漏！
//    NetManagerShare.sessionManager.requestSerializer.timeoutInterval = 120;
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    NetManagerShare.sessionManager.responseSerializer = response;
    
    AFJSONRequestSerializer *request = [AFJSONRequestSerializer serializer];
    NetManagerShare.sessionManager.requestSerializer = request;
    
    //设置请求头
    
    //TODO:请求头注视
    /*
    NSString *timeStr = [TooleClass getTime];
    NSString *requestStr = [NSString stringWithFormat:@"%@",[self dictionaryToMD5:parameters addTimesStr:timeStr]];

    NSDictionary *dic = @{@"Platform":@"iOS",@"Timestamp":timeStr,@"Sign":requestStr};
    [self setHttpHeaderFieldDictionary:dic];
    */
    if([UserData sharedUserData].loginState){//登陆成功会添加token
        NSString * author =[NSString stringWithFormat:@"BasicAuth+ %@",[UserData sharedUserData].user.AuthorityToken];
        [APIBase setValue:author forHTTPHeaderKey:@"Authorization"];
    }

    NetManagerShare.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/xml", @"text/plain", @"application/javascript", @"application/x-www-form-urlencoded", @"image/*", nil];
    
    NSURLSessionDataTask *task = nil;
    NetManagerShare.sessionManager.requestSerializer.timeoutInterval = 120;

    if (method == HttpRequestTypeGet) {
       
        task = [NetManagerShare.sessionManager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if([responseObject isKindOfClass:[NSDictionary class]]){
                responseSuccessBlock(task, responseObject);
            }else{
                if ([responseObject isKindOfClass:[NSData class]]) {//处理字符类型的
                    NSString * result = [[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    result = [result stringByReplacingOccurrencesOfString:@"\"" withString:@""];
                    responseSuccessBlock(task, result);
                }
                else{

                    NSError *err=nil;
                    err = responseObject;
                    responseFailBlock(task,err);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
    }else if(method==HttpRequestTypePost){
       
        task = [NetManagerShare.sessionManager  POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            responseSuccessBlock(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
    }else if (method == HttpRequestTypePut){
        
        task = [NetManagerShare.sessionManager PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             responseSuccessBlock(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            responseFailBlock(task,error);
        }];
        
    }else if (method == HttpRequestTypeDelete){
        
        task = [NetManagerShare.sessionManager DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
            responseSuccessBlock(task,responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             responseFailBlock(task,error);
        }];
    }
    
   
    return task;
}


- (void)setHttpHeaderFieldDictionary:(NSDictionary *)httpHeaderFieldDictionary
{
    _httpHeaderFieldDictionary = httpHeaderFieldDictionary;
    
    if (![httpHeaderFieldDictionary isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"请求头数据有误，请检查！");
        return;
    }
    NSArray *keyArray = httpHeaderFieldDictionary.allKeys;
    
    if (keyArray.count <= 0)
    {
        NSLog(@"请求头数据有误，请检查！");
        return;
    }
    
    for (NSInteger i = 0; i < keyArray.count; i ++)
    {
        NSString *keyString = keyArray[i];
        NSString *valueString = httpHeaderFieldDictionary[keyString];
        
        [APIBase setValue:valueString forHTTPHeaderKey:keyString];
    }
}

/**
 *  自定义请求头
 */
+ (void)setValue:(NSString *)value forHTTPHeaderKey:(NSString *)HTTPHeaderKey
{
    [NetManagerShare.sessionManager.requestSerializer setValue:value forHTTPHeaderField:HTTPHeaderKey];
}


/* 输出http响应的状态码 */
- (NSInteger)showResponseCode:(NSURLSessionDataTask *)task {
    NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
    //通讯协议状态码
    NSInteger statusCode = response.statusCode;
    NSLog(@"%ld", (long)statusCode);
    return statusCode;
}



#pragma mark-- 请求串 MD5
-(NSString *)dictionaryToMD5:(NSDictionary *)dict addTimesStr:(NSString *)timeStr{
    
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    [parameters addEntriesFromDictionary:dict];
    
    [parameters setValue:@"IJeHzP3EwFqdZYErHChCKpkmdkJCofLw" forKey:@"PublicKey"];
     [parameters setValue:timeStr forKey:@"Timestamp"];
    [parameters setValue:@"iOS" forKey:@"Platform"];
    NSMutableString *queryStr=[NSMutableString string];
    
    NSArray *sortedKeys = [[parameters allKeys] sortedArrayUsingSelector: @selector(compare:)];
    
    for (NSString *aKey in sortedKeys) {
        
        //[[parameters objectForKey:aKey] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//        if ([aKey isEqualToString:@"PlateNo"]) {
//            [queryStr appendFormat:@"%@=%@",aKey,[[parameters objectForKey:aKey] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ];
//        }else{
             [queryStr appendFormat:@"%@=%@",aKey,[parameters objectForKey:aKey] ];
//        }
       
       
        [queryStr appendString:@"&"];
    }
    NSRange range = NSMakeRange(0,([queryStr length]-1));
    NSString *_tem= [queryStr substringWithRange:range];
    return [self md5:_tem];
}
#pragma mark --字符串排序
- (NSString *)StringSort:(NSDictionary *)dict{
    
    
    NSDictionary *temDic=[NSDictionary dictionaryWithDictionary:dict];
    NSMutableString *queryStr=[NSMutableString string];
    
    NSArray *sortedKeys = [[temDic allKeys] sortedArrayUsingSelector: @selector(compare:)];
    
    for (NSString *aKey in sortedKeys) {
        [queryStr appendFormat:@"%@=%@",aKey,[dict objectForKey:aKey] ];
        [queryStr appendString:@"&"];
    }
    NSRange range = NSMakeRange(0,([queryStr length]-1));
    NSString *_tem= [queryStr substringWithRange:range];
    NSLog(@"去掉&的串:%@",_tem);
    return _tem;
    
}


#pragma mark MD5计算
- (NSString *)md5:(NSString *)str{
//    const char *cStr = [str UTF8String];
//    unsigned char digest[CC_MD5_DIGEST_LENGTH];
//
//    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
//
//    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
//    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
//        [result appendFormat:@"%02X", digest[i]];
//    }
//
//    return result;
    
    
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);

    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }

    return digest;
    
 
}



#pragma ---字典转json字符串

//字典转字符串
- (NSString *)dictionaryToString:(NSDictionary *)dictionary{
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
    NSString *s = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return s;
    
}

-(NSDictionary *)refineUsrWithDic:(NSDictionary *)parmDic{
    
//    UserInfo *user = [UserData sharedUserData].user;
    
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    [parameters addEntriesFromDictionary:parmDic];
    
//    if (user.Token.length != 0) {
//       [parameters setValue:user.Token forKey:@"Token"];
//    }else{
//       [parameters setValue:[TooleClass getDeviceID] forKey:@"UUID"];
//    }
    
    
    return parameters;
}




@end
